<template>
  <div>
    <el-card shadow="hover" class="main-el-card">
      <div ref="chartRef" :style="{ width: '100%', height: '300px' }"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Request from '@/api/request/request';
import urls from '@/api/request/urls';
import { useEChartsTheme } from '@/api/hooks/useEChartsTheme'; // 导入主题Hook

import * as echarts from 'echarts';
import { dictToMap, getDict } from '@/api/dict';

// 1. 创建ref引用
const chartRef = ref(null);

const xAxisData = ref<string[]>();
const seriesData = ref<string[]>();

//返回的图表类型接口
interface ChartItem {
  status: string;
  number: number;
}
//异步加载数据
const getData = async () => {
  const resData = await new Request(urls.BASEURLAPI + '/backstage/visualize/productionOrderStatusCountWithPriorityOrder', null, {
    params: {
      limit: 5
    }
  }).get();
  if (resData.success) {
    xAxisData.value = resData.data.map((item: ChartItem) => item.status);
    seriesData.value = resData.data.map((item: ChartItem) => item.number);
  }
};

// 初始化ECharts图表
const initChart = (title: string, themeName: string) => {
  if (chartRef.value) {
    const chart = echarts.init(chartRef.value, themeName);
    chart.setOption({
      title: {
        text: title
      },
      xAxis: { data: xAxisData.value },
      yAxis: {
        minInterval: 1 // 关键：强制最小间隔为1，确保刻度为整数
      },
      series: [
        {
          name: '订单量',
          label: {
            show: true,
            position: 'outside',
            formatter: function (params: any) {
              // 关键：通过formatter隐藏0值标签
              return params.value === 0 ? '' : params.value; // 值为0时不显示标签
            }
          },
          data: seriesData.value,
          type: 'bar'
        }
      ]
    });
  }
};

onMounted(async () => {
  // 1. 获取数据
  await getData();
  //2.对x轴的坐标值进行转换，从后端的英文状态改为中卫状态
  const carStopProductionDict = await getDict('汽车生产订单状态', 'string');
  xAxisData.value = xAxisData.value!.map((item: string) => dictToMap(carStopProductionDict).get(item) as string);
  // 2. 注册主题。两种方法都可以
  // const themeName = await useEChartsTheme('/theme/echarts/customized.json'); //放在public目录下
  const themeName = await useEChartsTheme(new URL(`@/assets/theme/echarts/walden.json`, import.meta.url).href); //放在asserts目录下
  //3.生成图表
  initChart('生产不同阶段订单数', themeName);
});
</script>

<style scoped>
/* .main-el-card {
  min-width: 200px;
  overflow: hidden;
  background-color: #64b0f2;
  color: #fff;
} */
</style>
